#region File Description
//-----------------------------------------------------------------------------
// MenuScreen.cs
//
// XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
//
// Modified by Hristo Hristov (30.09.11)
//
// Revision 4
#endregion

#region Using Statements
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input.Touch;
using Microsoft.Xna.Framework.Input;
using NOVA.ScreenManagement;
using System.Xml;
using NOVA.Utilities;
using System.Globalization;
using NOVA.UI;
#endregion

namespace NOVA.ScreenManagement.BaseScreens
{
    /// <summary>
    /// Base class for screens that contain a menu of options. The user can
    /// move up and down to select an entry, or cancel to back out of the screen.
    /// </summary>
    public abstract class MenuScreen : GameScreen
    {
        #region Fields

        List<MenuEntry> menuEntries = new List<MenuEntry>();
        protected int selectedEntry = 0;
        string titleText;
        Vector2 titlePosition;
        float titleScale;
        Color titleColor;

        Texture2D m_backgroundTexture;
        Color m_backgroundColor;


        #endregion

        #region Properties

        /// <summary>
        /// Gets the instance of the currently selected entry
        /// </summary>
        public MenuEntry SelectedEntry
        {
            get { return MenuEntries[selectedEntry]; }
        }

        /// <summary>
        /// Gets or sets the background color of the menu.
        /// </summary>
        public Color BackgroundColor
        {
            get { return m_backgroundColor; }
            set { m_backgroundColor = value; }
        }

        /// <summary>
        /// Gets or sets the background texture of the menu.
        /// </summary>
        public Texture2D BackgroundTexture
        {
            get { return m_backgroundTexture; }
            set { m_backgroundTexture = value; }
        }

        /// <summary>
        /// Gets or sets the menu title text.
        /// </summary>
        public string TitleText
        {
            get { return titleText; }
            set { titleText = value; }
        }

        /// <summary>
        /// Gets or sets the menu title scale.
        /// </summary>
        public float TitleScale
        {
            get { return titleScale; }
            set { titleScale = value; }
        }

        /// <summary>
        /// Gets or sets the menu title position.
        /// </summary>
        public Vector2 TitlePosition
        {
            get { return titlePosition; }
            set { titlePosition = value; }
        }

        /// <summary>
        /// Gets or sets the menu title color.
        /// </summary>
        public Color TitleColor
        {
            get { return titleColor; }
            set { titleColor = value; }
        }

        /// <summary>
        /// Gets the list of menu entries, so derived classes can add
        /// or change the menu contents.
        /// </summary>
        public List<MenuEntry> MenuEntries
        {
            get { return menuEntries; }
            set { menuEntries = value; }
        }


        #endregion

        #region Initialization


        /// <summary>
        /// Constructor.
        /// </summary>
        public MenuScreen(string title)
        {
            titleColor = Color.White;
            titlePosition = Vector2.One * -1;
            titleScale = 1f;
            titleText = title;

            m_backgroundColor = Color.CornflowerBlue;
            //m_backgroundTexture = Core.Content.Load<Texture2D>("background");

            TransitionOnTime = TimeSpan.FromSeconds(0.5);
            TransitionOffTime = TimeSpan.FromSeconds(0.5);
        }


        #endregion

        #region Handle Input


        /// <summary>
        /// Responds to user input, changing the selected entry and accepting
        /// or cancelling the menu.
        /// </summary>
        public override void HandleInput(InputState input)
        {
            // Move to the previous menu entry?
            if (input.IsMenuUp(ControllingPlayer))
            {
                selectedEntry--;

                if (selectedEntry < 0)
                    selectedEntry = menuEntries.Count - 1;
            }

            // Move to the next menu entry?
            if (input.IsMenuDown(ControllingPlayer))
            {
                selectedEntry++;

                if (selectedEntry >= menuEntries.Count)
                    selectedEntry = 0;
            }

            // Accept or cancel the menu? We pass in our ControllingPlayer, which may
            // either be null (to accept input from any player) or a specific index.
            // If we pass a null controlling player, the InputState helper returns to
            // us which player actually provided the input. We pass that through to
            // OnSelectEntry and OnCancel, so they can tell which player triggered them.
            PlayerIndex playerIndex;

            if (input.IsMenuSelect(ControllingPlayer, out playerIndex))
            {
                OnSelectEntry(selectedEntry, playerIndex);
            }
            else if (input.IsMenuCancel(ControllingPlayer, out playerIndex))
            {
                OnCancel(playerIndex);
            }
        }


        /// <summary>
        /// Handler for when the user has chosen a menu entry.
        /// </summary>
        protected virtual void OnSelectEntry(int entryIndex, PlayerIndex playerIndex)
        {
            menuEntries[entryIndex].OnSelectEntry(playerIndex);
        }


        /// <summary>
        /// Handler for when the user has cancelled the menu.
        /// </summary>
        protected virtual void OnCancel(PlayerIndex playerIndex)
        {
            ExitScreen();
        }


        /// <summary>
        /// Helper overload makes it easy to use OnCancel as a MenuEntry event handler.
        /// </summary>
        protected void OnCancel(object sender, PlayerIndexEventArgs e)
        {
            OnCancel(e.PlayerIndex);
        }


        #endregion

        #region Update and Draw


        /// <summary>
        /// Allows the screen the chance to position the menu entries. By default
        /// all menu entries are lined up in a vertical list, centered on the screen.
        /// </summary>
        protected virtual void UpdateMenuEntryLocations()
        {
            // Make the menu slide into place during transitions, using a
            // power curve to make things look more interesting (this makes
            // the movement slow down as it nears the end).
            float transitionOffset = (float)Math.Pow(TransitionPosition, 2);

            // start at Y = 175; each X value is generated per entry
            Vector2 position = new Vector2(0f, 175f);

            // update each menu entry's location in turn
            for (int i = 0; i < menuEntries.Count; i++)
            {
                MenuEntry menuEntry = menuEntries[i];

                // each entry is to be centered horizontally
                position.X = Core.ScreenManager.GraphicsDevice.Viewport.Width / 2 - menuEntry.GetWidth(this) / 2;
                
                if (ScreenState == ScreenState.TransitionOn)
                    position.X -= transitionOffset * 256 * 0.1f;
                else
                    position.X += transitionOffset * 512 * 0.1f;

                // set the entry's position
                menuEntry.Position = position;

                // move down for the next entry the size of this entry
                position.Y += menuEntry.GetHeight(this);
            }
        }


        /// <summary>
        /// Updates the menu.
        /// </summary>
        public override void Update(GameTime gameTime, bool otherScreenHasFocus,
                                                       bool coveredByOtherScreen)
        {
            base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);

            // Update each nested MenuEntry object.
            for (int i = 0; i < menuEntries.Count; i++)
            {
                bool isSelected = IsActive && (i == selectedEntry);

                menuEntries[i].Update(this, isSelected, gameTime);
            }
        }


        /// <summary>
        /// Draws the menu.
        /// </summary>
        public override void Draw(GameTime gameTime)
        {
            // make sure our entries are in the right place before we draw them
            UpdateMenuEntryLocations();

            GraphicsDevice graphics = Core.Device;//ScreenManager.GraphicsDevice;
            SpriteBatch spriteBatch = Core.ScreenManager.SpriteBatch;
            SpriteFont font = Core.ScreenManager.Font;

            spriteBatch.Begin();

            // Draw the background
            if (m_backgroundTexture != null)
            {
                Viewport viewport = Core.Device.Viewport;
                Rectangle fullscreen = new Rectangle(0, 0, viewport.Width, viewport.Height);
                
                if(m_backgroundColor != null)
                    spriteBatch.Draw(m_backgroundTexture, fullscreen, m_backgroundColor);
                else
                    spriteBatch.Draw(m_backgroundTexture, fullscreen, Color.White);
            }
            else if (m_backgroundColor != Color.Transparent)
            {
                Core.Device.Clear(m_backgroundColor);
            }

            // Draw each menu entry in turn.
            for (int i = 0; i < menuEntries.Count; i++)
            {
                MenuEntry menuEntry = menuEntries[i];

                bool isSelected = IsActive && (i == selectedEntry);

                menuEntry.Draw(this, isSelected, gameTime);
            }

            // Make the menu slide into place during transitions, using a
            // power curve to make things look more interesting (this makes
            // the movement slow down as it nears the end).
            float transitionOffset = (float)Math.Pow(TransitionPosition, 2);

            // Draw the menu title centered on the screen
            Vector2 position;
            Vector2 origin;

            if (titlePosition.X >= 0 || titlePosition.Y >= 0)
            {
                position = titlePosition;
                origin = Vector2.Zero;
            }
            else
            {
                position = new Vector2(graphics.Viewport.Width / 2, 80);
                origin = font.MeasureString(titleText) / 2;
            }
            
            Color color = titleColor * TransitionAlpha;

            position.Y -= transitionOffset * 100;

            spriteBatch.DrawString(font, titleText, position, color, 0,
                                   origin, titleScale, SpriteEffects.None, 0);

            spriteBatch.End();

            // Show additional 2D UIs
            UI2DRenderer.Flush(true, 0);
        }


        #endregion

        #region Public Methods

        /// <summary>
        /// Saves the current menu arrangement to the given file in XML.
        /// </summary>
        public void Save(string filename)
        {
            XmlDocument xmlDoc = new XmlDocument();
            XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null);

            xmlDoc.InsertBefore(xmlDeclaration, xmlDoc.DocumentElement);

            XmlElement xmlRootNode = xmlDoc.CreateElement("Menu");
            xmlDoc.AppendChild(xmlRootNode);
            
            XmlElement xmlTitleNode = xmlDoc.CreateElement("Title");
            xmlRootNode.AppendChild(xmlTitleNode);

            XmlAttribute xmlTitleTextAtt = xmlDoc.CreateAttribute("Text");
            xmlTitleTextAtt.InnerText = titleText;
            xmlTitleNode.Attributes.Append(xmlTitleTextAtt);

            XmlAttribute xmlTitlePositionAtt = xmlDoc.CreateAttribute("Position");
            xmlTitlePositionAtt.InnerText = Helpers.Vector2ToString(titlePosition);
            xmlTitleNode.Attributes.Append(xmlTitlePositionAtt);

            XmlAttribute xmlTitleScaleAtt = xmlDoc.CreateAttribute("Scale");
            xmlTitleScaleAtt.InnerText = titleScale.ToString();
            xmlTitleNode.Attributes.Append(xmlTitleScaleAtt);

            XmlAttribute xmlTitleColorAtt = xmlDoc.CreateAttribute("Color");
            xmlTitleColorAtt.InnerText = Helpers.Vector3ToString(titleColor.ToVector3());
            xmlTitleNode.Attributes.Append(xmlTitleColorAtt);

            #region Entries
            XmlElement xmlEntriesNode = xmlDoc.CreateElement("Entries");
            xmlRootNode.AppendChild(xmlEntriesNode);
            
            foreach (MenuEntry entry in menuEntries)
            {
                XmlNode xmlObjNode = xmlDoc.CreateElement("Entry");
                xmlEntriesNode.AppendChild(xmlObjNode);

                // Text
                XmlAttribute xmlTextAtt = xmlDoc.CreateAttribute("Text");
                xmlTextAtt.InnerText = entry.Text;
                xmlObjNode.Attributes.Append(xmlTextAtt);

                // Position
                XmlAttribute xmlPosAtt = xmlDoc.CreateAttribute("Position");
                xmlPosAtt.InnerText = Helpers.Vector2ToString(entry.Position);
                xmlObjNode.Attributes.Append(xmlPosAtt);

                // Color
                XmlAttribute xmlColorAtt = xmlDoc.CreateAttribute("Color");
                xmlColorAtt.InnerText = Helpers.Vector3ToString(entry.Color.ToVector3());
                xmlObjNode.Attributes.Append(xmlColorAtt);

                // Rotation
                XmlAttribute xmlRotationAtt = xmlDoc.CreateAttribute("Rotation");
                xmlRotationAtt.InnerText = entry.Rotation.ToString(NumberFormatInfo.InvariantInfo);
                xmlObjNode.Attributes.Append(xmlRotationAtt);

                // Scale
                XmlAttribute xmlScaleAtt = xmlDoc.CreateAttribute("Scale");
                xmlScaleAtt.InnerText = entry.Scale.ToString(NumberFormatInfo.InvariantInfo);
                xmlObjNode.Attributes.Append(xmlScaleAtt);                
            }
            #endregion

            try
            {
                xmlDoc.Save(filename);
            }
            catch (Exception exp)
            {
#if !DEBUG
                System.Windows.Forms.MessageBox.Show("Failed to save the menu as " + filename, "Error", System.Windows.Forms.MessageBoxButtons.OK);
#else
                throw new Exception(exp.Message);
#endif
            }
        }

        /// <summary>
        /// Loads a menu from a given xml file.
        /// </summary>
        public void Load(string filename)
        {
            XmlDocument xmlDoc = new XmlDocument();

            try
            {
                xmlDoc.Load(filename);
            }
            catch (Exception exp)
            {
#if !DEBUG
                System.Windows.Forms.MessageBox.Show("Failed to load scene from " + filename, "Error", System.Windows.Forms.MessageBoxButtons.OK);
#else
                throw new Exception(exp.Message);
#endif
            }

            XmlNode rootNode;

            if (xmlDoc.ChildNodes[1].Name.Equals("Menu"))
            {
                rootNode = xmlDoc.ChildNodes[1] as XmlNode;

                menuEntries.Clear();
            }
            else
            {
#if !DEBUG
                System.Windows.Forms.MessageBox.Show("Failed to load scene from " + filename, "Error", System.Windows.Forms.MessageBoxButtons.OK);
#else
                throw new Exception("Failed to load menu from " + filename);
#endif
            }


            //if (xmlDoc.ChildNodes[2].Name.Equals("Entries"))
            {
                // Menu Entries
                foreach (XmlNode att in xmlDoc.ChildNodes[1].ChildNodes)
                {
                    if (att.Name.Equals("Title"))
                    {
                        foreach (XmlAttribute entryXmlNode in att.Attributes)
                        {
                            if (entryXmlNode.Name == "Text")
                                titleText = entryXmlNode.Value;

                            if (entryXmlNode.Name == "Position")
                                titlePosition = Helpers.StringToVector2(entryXmlNode.Value);

                            if (entryXmlNode.Name == "Scale")
                                titleScale = float.Parse(entryXmlNode.Value);

                            if (entryXmlNode.Name == "Color")
                            {
                                Vector3 vec = Helpers.StringToVector3(entryXmlNode.Value);
                                titleColor = new Color(vec.X, vec.Y, vec.Z);
                            }
                        }
                    }
                    else
                    {
                        if (att.Name.Equals("Entries"))
                        {
                            foreach (XmlNode entryNode in att.ChildNodes)
                            {
                                MenuEntry entry = new MenuEntry("");

                                foreach (XmlAttribute entryXmlNode in entryNode.Attributes)
                                {
                                    if (entryXmlNode.Name == "Text")
                                        entry.Text = entryXmlNode.Value;

                                    if (entryXmlNode.Name == "Position")
                                        entry.Position = Helpers.StringToVector2(entryXmlNode.Value);

                                    if (entryXmlNode.Name == "Color")
                                    {
                                        Vector3 vec = Helpers.StringToVector3(entryXmlNode.Value);
                                        entry.Color = new Color(vec.X, vec.Y, vec.Z);
                                    }

                                    if (entryXmlNode.Name == "Rotation")
                                        entry.Rotation = float.Parse(entryXmlNode.Value);

                                    if (entryXmlNode.Name == "Scale")
                                        entry.Scale = float.Parse(entryXmlNode.Value);
                                }

                                menuEntries.Add(entry);
                            }                            
                        }
                    }
                }
            }            
        }

        #endregion
    }
}

